package com.pocket.insight.base.sql.dialect;

import com.pocket.insight.base.mql.TypedVal;
import org.apache.commons.lang3.StringUtils;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/12/5
 */
public class PostgresqlDialect extends BaseDialect{

    /********************************* 1. 标识符差异配置 *********************************/
    @Override
    public String getLeftQuoteChar() {
        return "\"";
    }

    @Override
    public String quoteSingle(String entity) {
        return String.format("\"%s\"", StringUtils.replace(entity, "\"", ""));
    }

    /********************************* 2. TODO *********************************/


    @Override
    public TypedVal setPage(TypedVal query, Long offset, Long limit) {
        if (query == null) {
            return new TypedVal();
        }
        if (StringUtils.isEmpty(query.getStr())) {
            return query;
        }
        String sql = query.getStr();
        StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
        sqlBuilder.append(sql);
        if (offset.longValue() == 0L) {
            sqlBuilder.append(" limit ");
            sqlBuilder.append(limit);
        } else {
            sqlBuilder.append(" offset ");
            sqlBuilder.append(offset);
            sqlBuilder.append(" limit ");
            sqlBuilder.append(limit);
        }
        return new TypedVal(sqlBuilder.toString());
    }


    @Override
    public boolean isJsonAvailable() {
        return (this.majorVersion == 0L || this.majorVersion > 8L || (this.majorVersion == 8L && this.minorVersion > 2L));
    }

    @Override
    public boolean isBoolAvailable() {
        return false;
    }

    @Override
    public Object jodaToNativeParseFormat(String jodaFormat) {
        return jodaFormat
                .replace("yyyy", "YYYY")
                .replace("yy", "YY")
                .replace("MMMM", "Month")
                .replace("MMM", "Mon")
                .replace("d", "D")
                .replace("HH", "HH24")
                .replace("mm", "MI")
                .replace("SSS", "MS")
                .replace("SS", "MS")
                .replace("'T'", "\"T\"")
                .replace("'Z'", "\"Z\"");
    }
}
